<?php

/**
 * Description of ContattiController
 *
 * @author luigi.pastore
 * @created  16-mag-2011
 */
class PartnersController extends Classes_Controller
{
    public function init()
    {
	$this->model_partner	= new Classes_Partner();
	$this->model_province	= new Classes_Province();

	$this->partner_types = $this->application->getResource( 'PartnerTypes' );
	$this->contact_roles = $this->application->getResource( 'ContactRoles' );
        
	$this->province = $this->model_province->fetchAll();
	
	$this->layout->province = $this->province;
	$this->layout->partner_types = $this->partner_types;
        $this->layout->contact_roles = $this->contact_roles;
	
        // Dati Form
        $this->form_data = $this->getParams();
        
	// Edit...
	if( is_numeric( $id = $this->getParam( 'id' ) ) )
	{
	    // Fetch
	    $partner = $this->model_partner->fetchById( array( $id ) );

	    if( empty( $partner ) )
		trigger_error( 'Nessuna partner' );
	    
	    $this->partner = array_shift( $partner );

            # Assegniamo i dati al layout
        
            // Format..
            list( $this->partner['partner_phone_prefix'], $this->partner['partner_phone_number'] ) = explode( '/', $this->partner['partner_phone'] );
            list( $this->partner['partner_fax_prefix'], $this->partner['partner_fax_number'] ) = explode( '/', $this->partner['partner_fax'] );            
            $this->partner['partner_types'] = explode( ';', $this->partner['partner_types'] );

	    $this->layout->partner_id = $this->partner['partner_id'];
	}        

        // Se sto editando precompilo la sessione
        if( !empty( $this->form_data['salva'] ) )
            $this->partner = array_merge( (array) $this->partner, $this->form_data );
        
        $this->layout->data = $this->partner;
    }
    
    public function indexAction()
    {
        $this->layout->count = $this->model_partner->getCount();
	$this->layout->content = array( 'script' => 'partners/index' );
    }
    
    public function infoAction()
    {
        if( $this->form_data['salva'] AND $this->form_data['salva'] !== '' )
	{
            // Mapping...
            $data = array(
                'partner_id'		=> $this->partner['partner_id'],
                'partner_types'         => $this->form_data['partner_types'],
                'partner_name'          => $this->form_data['partner_name'],
                'partner_email'		=> $this->form_data['partner_email'],
                'partner_phone'		=> ( $this->form_data['partner_phone_prefix'] != '' OR $this->form_data['partner_phone_number'] != '' ) ? ( $this->form_data['partner_phone_prefix'] .'/'. $this->form_data['partner_phone_number'] ) : '',
                'partner_fax'		=> ( $this->form_data['partner_fax_prefix'] != '' OR $this->form_data['partner_fax_number'] != '' ) ? ( $this->form_data['partner_fax_prefix'] .'/'. $this->form_data['partner_fax_number'] ) : '',
                'partner_city'		=> $this->form_data['partner_city'],
                'partner_cap'		=> $this->form_data['partner_cap'],
                'partner_loc'		=> $this->form_data['partner_loc'],
                'partner_street'	=> $this->form_data['partner_street'],
                'partner_street_number'	=> $this->form_data['partner_street_number'],
                'partner_province_id'	=> $this->form_data['partner_province_id'],		    
                'partner_notes'		=> $this->form_data['partner_notes']
            );

            // Edit o Aggiunta?
            if( empty( $this->partner['partner_id'] ) )
                $data['partner_createdby'] = $this->application->auth->user['user_id'];
            else
                $data['partner_modifiedby'] = $this->application->auth->user['user_id'];

            $model = new Classes_Partner( $data );
            
            if( is_numeric( $partner_id = $model->save()->partner_id ) )
            {
                // Redirect...
                return header( 'Location: /admin/partners/riepilogo/id/' . $partner_id );
            }
            else
            {
                $errorMsg = $model->errors;

                if( $model->errors['partner_name'] )
                    $errorMsg['partner_name'] = ERR_EMPTY;

                if( $model->errors['partner_email'] )
                    $errorMsg['partner_email'] = sprintf( ERR_FORMAT, 'Email' );

                if( $model->errors['partner_phone'] )
                    $errorMsg['partner_phone'] = sprintf( ERR_FORMAT, 'Tel. Principale' );

                if( $model->errors['partner_fax'] )
                    $errorMsg['partner_fax'] = sprintf( ERR_FORMAT, 'Fax' );
                                
                if( $model->errors['partner_types'] )
                    $errorMsg['partner_types'] = sprintf( ERR_EMPTY_SELECT, 'Tipo' );

                if( $model->errors['partner_city'] )
                    $errorMsg['partner_address'] = sprintf( ERR_EMPTY_FIELD, 'Citt&agrave;' );

                if( $model->errors['partner_cap'] )
                    $errorMsg['partner_address'] = sprintf( ERR_FORMAT, 'Cap' );

                if( $model->errors['partner_province_id'] )
                    $errorMsg['partner_address'] = sprintf( ERR_EMPTY_SELECT, 'Provincia' );
            }          
	}
                
        $this->layout->errorMsg = $errorMsg;
	$this->layout->content	= array( 'script' => 'partners/info' );        
    }
    
    public function riepilogoAction()
    {
	if( empty( $this->partner ) )
	    trigger_error( 'Nessun contatto Selezionato' );

        # Assegniamo i dati al layout
        $this->layout->content = array( 'script' => 'partners/riepilogo' );
    }     
    
    public function vediAction()
    {
	// Se non c'è il post lancia l'errore
	if( !is_array( $this->partner ) )
	{
	    trigger_error( 'Errore Associa Contatto', E_USER_WARNING );
	}
	
	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'partners/vedi' );		
    }

    public function associacontattiAction()
    {
	// Se non c'è il post lancia l'errore
	if( !is_array( $this->partner ) )
            return header( 'Location: /admin/partners/info' );

	if( $this->form_data['salva'] AND $this->form_data['salva'] !== '' )
	{
	    $roles = array();
	    
            if( count( $this->form_data['contacts'] ) > 0 )
            {
                foreach( $this->form_data['contacts'] AS $key => $value )
                {
                    foreach( $value as $role ){
                        // Mapping...
                        $roles[] = array( 'fab_contacts_contact_id' => $key, 'fab_contacts_role' => $role );
                        
                    }
                }
            }
	    
	    if( !$errorMsg )
	    {
		$model = new Classes_Partner( array( 'partner_id' => $this->partner['partner_id'] ) );
		
                if( is_numeric( $partner_id = $model->saveExtra( array( 'contacts' => $roles ) )->partner_id ) AND !$model->errors )
                {
                    // Redirect...
                    return header( 'Location: /admin/partners/riepilogo/id/' . $partner_id );
                }
                else
                {
                    if( $model->errors )
                        $errorMsg = $model->errors;
                }
	    }
	}

	$this->layout->errorMsg	    = $errorMsg;
	$this->layout->content	    = array( 'script' => 'partners/associa-contatti' );		
    }

    public function rubricaAction()
    {
	$this->layout->partners = $this->model_partner->fetchAll();
	$this->layout->content = array( 'script' => 'partners/rubrica' );
    }
    
    private function checkFormData( $data )
    {
	if( !filter_var( $data['partner_name'], FILTER_SANITIZE_STRING ) )
	    $errorMsg['partner_name'] = sprintf( ERR_FORMAT, 'Denominazione' );

	if( !$data['partner_types'] )
	    $errorMsg['partner_types'] = ERR_EMPTY;

	/* Info Opzionali */
	if( $data['partner_email'] !== '' AND !filter_var( $data['partner_email'], FILTER_VALIDATE_EMAIL ) )
	    $errorMsg['partner_email'] = sprintf( ERR_FORMAT, 'Email' );

	if( $data['partner_cap'] !== '' AND ( ( strlen( $data['partner_cap'] ) != 0 AND strlen( $data['partner_cap'] ) != 5 ) OR ( !filter_var( $data['partner_cap'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]{5}$/" ) ) ) ) ) )
	    $errorMsg['partner_address'] = sprintf( ERR_FORMAT, 'CAP' );

	if( ( $data['partner_phone_prefix'] !== '' OR $data['partner_phone_number'] !== '' ) AND ( !filter_var( $data['partner_phone_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]*$/" ) ) ) OR !filter_var( $data['partner_phone_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/[0-9]*/" ) ) ) ) )
	    $errorMsg['partner_mobile'] = sprintf( ERR_FORMAT, 'Tel. Privato' );
	
	if( ( $data['partner_fax_prefix'] !== '' OR $data['partner_fax_number'] !== '' ) AND ( !filter_var( $data['partner_fax_prefix'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/^[0-9]*$/" ) ) ) OR !filter_var( $data['partner_fax_number'], FILTER_VALIDATE_REGEXP, array( 'options' => array( 'regexp' => "/[0-9]*/" ) ) ) ) )
	    $errorMsg['partner_fax'] = sprintf( ERR_FORMAT, 'Fax' );	
	
	return $errorMsg ? $errorMsg : false;
    }
}